package com.imis.base.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.imis.base.util.ConvertUtils;
import com.imis.module.system.model.po.SysUser;
import com.imis.module.system.service.ISysUserService;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <p>
 * AutoFillFieldsMetaObjectHandler<br>
 * 自动填充字段元对象处理程序<br>
 * 自动注入创建人、创建时间、修改人、修改时间
 * </p>
 *
 * @author XinLau
 * @version 1.0
 * @since 2021年01月20日 13:24
 */
@Component
public class AutoFillFieldsMetaObjectHandler implements MetaObjectHandler {

    /**
     * 用户信息 服务类
     */
    private ISysUserService sysUserService;

    @Autowired
    public void setSysUserService(ISysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    /**
     * 插入数据时的填充策略
     *
     * @param metaObject - 元对象
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2021/1/20 13:30
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (ConvertUtils.isEmpty(getFieldValByName(com.imis.base.constant.DataBaseConstant.CREATE_BY, metaObject))) {
            // 获取当前登录用户的编号
            SysUser sysUser = sysUserService.queryUserByName(com.imis.base.util.CurrentUserUtils.getUserNameByToken());
            Long userId = ConvertUtils.isEmpty(sysUser) ? 0 : sysUser.getId();
            setFieldValByName(com.imis.base.constant.DataBaseConstant.CREATE_BY, userId, metaObject);
        }
        this.setFieldValByName(com.imis.base.constant.DataBaseConstant.CREATE_TIME, java.time.LocalDateTime.now(), metaObject);
    }

    /**
     * 更新数据时的填充策略
     *
     * @param metaObject - 元对象
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2021/1/20 13:30
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if (ConvertUtils.isEmpty(getFieldValByName(com.imis.base.constant.DataBaseConstant.UPDATE_BY, metaObject))) {
            // 获取当前登录用户的编号
            SysUser sysUser = sysUserService.queryUserByName(com.imis.base.util.CurrentUserUtils.getUserNameByToken());
            Long userId = ConvertUtils.isEmpty(sysUser) ? 0 : sysUser.getId();
            setFieldValByName(com.imis.base.constant.DataBaseConstant.UPDATE_BY, userId, metaObject);
        }
        this.setFieldValByName(com.imis.base.constant.DataBaseConstant.UPDATE_TIME, java.time.LocalDateTime.now(), metaObject);
    }

}
